package edu.stanford.bmir.protege.web.server.stkosutil.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.stanford.bmir.protege.web.server.owlapi.OWLAPIProject;
import edu.stanford.bmir.protege.web.server.owlapi.OWLAPIProjectManager;
import edu.stanford.bmir.protege.web.shared.project.ProjectId;

public abstract class StkosUtilBaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public static final String CONTENTTYPE_JSON = "application/json";
	public static final String CONTENTTYPE_TEXT = "text/plain";
	public static final String CONTENTTYPE_XML = "text/xml";
	public static final String CONTENTTYPE_HTML = "text/html";

	public static final String CHARSET_UTF8 = "UTF-8";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected abstract void doPost(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException;

	protected OWLAPIProject getProject(String projectName) {
		if (projectName == null) {
			return null;
		}
		ProjectId projectId = ProjectId.get(projectName);
		return getProject(projectId);
	}

	protected OWLAPIProject getProject(ProjectId projectId) {
		OWLAPIProjectManager pm = OWLAPIProjectManager.getProjectManager();
		return pm.getProject(projectId);
	}

	protected void writeJson_utf8(String json, HttpServletResponse resp) {
		write(CONTENTTYPE_JSON, CHARSET_UTF8, json, resp);
	}

	protected void writeText_utf8(String text, HttpServletResponse resp) {
		write(CONTENTTYPE_TEXT, CHARSET_UTF8, text, resp);
	}

	protected void writeXml_utf8(String xml, HttpServletResponse resp) {
		write(CONTENTTYPE_XML, CHARSET_UTF8, xml, resp);
	}

	protected void writeHtml_utf8(String html, HttpServletResponse resp) {
		write(CONTENTTYPE_HTML, CHARSET_UTF8, html, resp);
	}

	protected void write(String contentType, String charset, String content,
			HttpServletResponse resp) {
		resp.setContentType(contentType + ";" + charset);
		PrintWriter out = null;
		try {
			out = resp.getWriter();
			out.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}
}
